package com.module.record.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.module.basic.domain.BasicDevice;
import com.module.basic.mapper.BasicDeviceMapper;
import com.module.common.utils.DateUtils;
import com.module.common.utils.StringUtils;
import com.module.common.utils.bean.BeanUtils;
import com.module.influxdb.service.InfluxDBService;
import com.module.record.domain.RecordOnline;
import com.module.record.domain.RecordReading;
import com.module.record.domain.vo.RecordOnlineVO;
import com.module.record.domain.vo.RecordReadingVO;
import com.module.record.mapper.RecordOnlineMapper;
import com.module.record.service.IRecordOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 设备上下线记录
 */
@Service
public class RecordOnlineServiceImpl extends ServiceImpl<RecordOnlineMapper, RecordOnlineVO> implements IRecordOnlineService {

    @Autowired
    private BasicDeviceMapper basicDeviceMapper;

    @Autowired
    private InfluxDBService influxDBService;

    /**
     * 设备上下线记录查询
     * @param recordOnlineVO
     * @return
     */
    @Override
    public List<RecordOnlineVO> selectRecordOnlineList(RecordOnlineVO recordOnlineVO) {
        StringBuilder queryCondition = new StringBuilder();
        queryCondition.append(" 1 = 1");
        if (StringUtils.isNotEmpty(recordOnlineVO.getDeviceImei())) {
            queryCondition.append(" and device_imei =~/").append(recordOnlineVO.getDeviceImei()).append("/");
        }
        if (StringUtils.isNotEmpty(recordOnlineVO.getOnlineStatus())) {
            queryCondition.append(" and online_status = '").append(recordOnlineVO.getOnlineStatus()).append("'");
        }
        if (StringUtils.isNotNull(recordOnlineVO.getParams().get("beginTime"))) {
            queryCondition.append(" and time >= '").append(recordOnlineVO.getParams().get("beginTime")).append(" 00:00:00'");
        }
        if (StringUtils.isNotNull(recordOnlineVO.getParams().get("endTime"))) {
            queryCondition.append(" and time <= '").append(recordOnlineVO.getParams().get("endTime")).append(" 23:59:59'");
        }
        List<RecordOnline> onlineList = influxDBService.fetchResults("device_imei, online_status, remark, time", "record_online", queryCondition.toString(), "time desc", RecordOnline.class);
        List<RecordOnlineVO> resultList = new ArrayList<RecordOnlineVO>();
        for (RecordOnline recordOnline : onlineList) {
            RecordOnlineVO onlineVO = new RecordOnlineVO();
            BeanUtils.copyBeanProp(onlineVO, recordOnline);
            onlineVO.setCreateTime(DateUtils.parseUTCDate(recordOnline.getTime()));
            resultList.add(onlineVO);
        }
        return resultList;
    }

    /**
     * 保存设备上线记录
     *
     * @param onlineJson
     */
    @Override
    public void insertRecordOnline(JSONObject onlineJson) {
        BasicDevice basicDevice = basicDeviceMapper.selectOne(Wrappers.lambdaQuery(BasicDevice.class)
                .eq(BasicDevice::getDeviceImei, onlineJson.getString("deviceImei")).last("limit 1"));
        if(StringUtils.isNull(basicDevice)) {
            basicDevice = new BasicDevice();
            basicDevice.setDeviceImei(onlineJson.getString("deviceImei"));
            basicDevice.setDeviceType(onlineJson.getString("deviceType"));
            if(onlineJson.getString("deviceType").equals("4G")) {
                basicDevice.setDeviceIccid(onlineJson.getString("deviceIccid"));
                basicDevice.setDeviceVer(onlineJson.getString("deviceVer"));
                basicDevice.setDeviceCsq(onlineJson.getString("deviceCsq"));
            }
            basicDevice.setOnlineStatus("online");
            basicDevice.setOnlineTime(DateUtils.getNowDate());
            basicDevice.setCreateTime(DateUtils.getNowDate());
            basicDeviceMapper.insert(basicDevice);
        } else {
            if(onlineJson.getString("deviceType").equals("4G")) {
                basicDevice.setDeviceIccid(onlineJson.getString("deviceIccid"));
                basicDevice.setDeviceVer(onlineJson.getString("deviceVer"));
                basicDevice.setDeviceCsq(onlineJson.getString("deviceCsq"));
            }
            basicDevice.setOnlineStatus("online");
            basicDevice.setOnlineTime(DateUtils.getNowDate());
            basicDeviceMapper.updateById(basicDevice);
        }

        RecordOnline recordOnline = new RecordOnline();
        recordOnline.setDeviceImei(onlineJson.getString("deviceImei"));
        recordOnline.setOnlineStatus("online");
        recordOnline.setRemark(onlineJson.getString("remark"));
        influxDBService.insertOne(recordOnline);
    }

    /**
     * 保存设备下线记录
     *
     * @param offlineJson
     */
    @Override
    public void insertRecordOffline(JSONObject offlineJson) {
        LambdaUpdateWrapper<BasicDevice> updateWrapper = Wrappers.lambdaUpdate();
        updateWrapper.set(BasicDevice::getOnlineStatus, "offline");
        updateWrapper.set(BasicDevice::getOfflineTime, DateUtils.getNowDate());
        updateWrapper.eq(BasicDevice::getDeviceImei, offlineJson.getString("deviceImei"));
        basicDeviceMapper.update(null, updateWrapper);

        RecordOnline recordOnline = new RecordOnline();
        recordOnline.setDeviceImei(offlineJson.getString("deviceImei"));
        recordOnline.setOnlineStatus("offline");
        recordOnline.setRemark(offlineJson.getString("remark"));
        influxDBService.insertOne(recordOnline);
    }

    /**
     * 清理上下线记录
     */
    @Override
    public void cleanRecordOnline() {
        influxDBService.cleanMeasurement("record_online");
    }
}
